<template>
  <div class="upload-container">
    <!-- 显示图片 -->
    <div v-if="value" class="preview-image">
      <img :src="value" class="avatar" />
      <i class="el-icon-delete" @click="removePhoto"></i>
    </div>
    <!-- 上传按钮 -->
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="uploadImage"
    >
      <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import COS from "cos-js-sdk-v5";

export default {
  props: {
    value: {
      type: String,
      default: "",
    },
  },
  methods: {
    uploadImage(data) {
      const cos = new COS({
        // 腾讯云的密钥id
        SecretId: "AKIDmPr6rTt780g9OR1Uo5FD9sPRGrLejaEg",
        // 腾讯云的密钥
        SecretKey: "JPJ0WpGW8YlpjSyGShqocWI4sXDmCPPX",
      });
      cos.putObject(
        {
          Bucket: "yysftwo-1341723392", // 存储桶名称
          Region: "ap-guangzhou", // 存储桶所在地域
          Key: data.file.name, // 上传到存储桶的路径
          StorageClass: "STANDARD", // 存储类型
          Body: data.file, // 上传的文件对象
        },
        (err, data) => {
          if (err) {
            this.$message.error("上传失败：" + err.message);
            return;
          }
          if (data.statusCode === 200 && data.Location) {
            // 拿到了腾讯云返回的地址
            // 通过input自定义事件将地址传出去
            this.$emit("input", "https://" + data.Location);
          }
        }
      );
    },
    beforeAvatarUpload(file) {
      const isValidType = [
        "image/jpeg",
        "image/png",
        "image/gif",
        "image/bmp",
      ].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isValidType) {
        this.$message.error("上传头像图片只能是 JPG/PNG/GIF/BMP 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isValidType && isLt2M;
    },
    removePhoto() {
      this.$emit("input", "");
    },
  },
};
</script>

<style lang="scss" scoped>
.upload-container {
  display: flex;
  align-items: center;
  .preview-image {
    position: relative;
    margin-right: 20px;
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-icon-delete {
      position: absolute;
      top: -8px;
      right: -8px;
      color: red;
      cursor: pointer;
    }
  }
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    &:hover {
      border-color: #409eff;
    }
  }
}
</style>